package net.airtheva.uniqueTask5;

import java.util.ArrayList;
import java.util.Iterator;

import net.airtheva.uniqueTask5.utils.Utils;
import net.airtheva.weather.Constants;
import net.airtheva.weather.Location;
import net.airtheva.weather.Weather;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;


public class WeatherService extends Service {

	public static final String TAG = "WeatherService";
	
	public static final String NAME_SHARED_PREFERENCES = "sharedPreferences";
	
	public static final String KEY_LOCATION_NAMES = "locationNames";
	public static final String KEY_APP_WIDGET_CONFIGURATIONS = "appWidgetConfigurations";
	
	public static final String BROADCAST_ACTION_APPWIDGET_REQUEST = "net.airtheva.uniqueTask5.APPWIDGET_REQUEST";
	public static final String BROADCAST_ACTION_APPWIDGET_UPDATE = "net.airtheva.uniqueTask5.APPWIDGET_UPDATE";
	
	class _Binder extends Binder {

		WeatherService GetServive() {
			return WeatherService.this;
		}
		
	}
	
	class _BroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				Log.d(TAG, "onReceive.");
				
				int appWidgetID = intent.getIntExtra(WeatherWidget.KEY_APP_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
				
				SharedPreferences sharedPreferences = getSharedPreferences(NAME_SHARED_PREFERENCES, MODE_PRIVATE);
				JSONObject appWidgetConfigurations = new JSONObject(sharedPreferences.getString(KEY_APP_WIDGET_CONFIGURATIONS, "{}"));
				
				int position = appWidgetConfigurations.getInt(appWidgetID + "");
				
				UpdateWidget(appWidgetID, position);
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	
	_Binder mBinder;
	
	_BroadcastReceiver mBroadcastReceiver;
	
	public Location CurrentLocation;
	
	public ArrayList<Location> Locations;
	
	public boolean IsRefreshing = false;
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
		mBinder = new _Binder();
		
		mBroadcastReceiver = new _BroadcastReceiver();
		
		CurrentLocation = new Location("北京");
		
		Locations = new ArrayList<Location>();
		Locations.add(CurrentLocation);

		LoadLocations();
		
		registerReceiver(mBroadcastReceiver, new IntentFilter(BROADCAST_ACTION_APPWIDGET_REQUEST));
		
		UpdateWidgets();
		
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}
	
	@Override
	public void onDestroy() {
		unregisterReceiver(mBroadcastReceiver);
		super.onDestroy();
	}

	public void LoadLocations() {
		
		try {
			SharedPreferences sharedPreferences = getSharedPreferences(NAME_SHARED_PREFERENCES, MODE_PRIVATE);
			
			Locations.clear();
			
			Locations.add(CurrentLocation);
			
			JSONArray locationNames = new JSONArray(sharedPreferences.getString(KEY_LOCATION_NAMES, "[]"));
			
			if(locationNames.length() > 0) {
				
				CurrentLocation.Name = locationNames.getString(0);
				
				int size = locationNames.length();
				for(int i = 1; i < size; i++) {
					String locationName = locationNames.getString(i);
					Location location = new Location(locationName);
					Locations.add(location);
				}
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public void SaveLocations() {
		
		SharedPreferences.Editor editor = getSharedPreferences(NAME_SHARED_PREFERENCES, MODE_PRIVATE).edit();
		
		JSONArray locationNames = new JSONArray();
		
		int size = Locations.size();
		for(int i = 0; i < size; i++) {
			
			Location location = Locations.get(i);
			locationNames.put(location.Name);
			
		}
		
		editor.putString(KEY_LOCATION_NAMES, locationNames.toString());
		
		editor.apply();
		
	}

	public void AddLocation(String locationName) {
		Locations.add(new Location(locationName));
	}
	
	public void RefreshWeather(Location location) {
		
		try {

			IsRefreshing = true;
			
			DefaultHttpClient dhc = new DefaultHttpClient();
			HttpGet hg = new HttpGet("http://m.weather.com.cn/data/" + Constants.FindLocationCode(location.Name) + ".html");
			Log.d(TAG, "Request start!");
			HttpResponse hr = dhc.execute(hg);
			Log.d(TAG, "Request end!");

			String j = new String(Utils.InputStreamToBytes(hr.getEntity().getContent()));

			JSONObject jj = new JSONObject(j);

			location.Update(this, jj);

		} catch (Exception e) {
			e.printStackTrace();
		}
		
		IsRefreshing = false;
		
		UpdateWidgets();
		
	}
	
	public void UpdateWidget(int appWidgetID, int position) {
		
		Location location = Locations.get(position);
		Weather weather = location.Weathers[0];
		
		Intent intent = new Intent(BROADCAST_ACTION_APPWIDGET_UPDATE);
		
		intent.putExtra(WeatherWidget.KEY_APP_WIDGET_ID, appWidgetID);
		
		if(weather != null) {
			intent.putExtra(WeatherWidget.KEY_WEATHER_ICON_URI, weather.WeatherIconURI);
			intent.putExtra(WeatherWidget.KEY_LOCATION_NAME, location.Name);
			intent.putExtra(WeatherWidget.KEY_WEATHER, weather.Weather);
			intent.putExtra(WeatherWidget.KEY_TEMPERATURE, weather.TemperatureCelsius);
		}
		else {
			intent.putExtra(WeatherWidget.KEY_WEATHER_ICON_URI, "");
			intent.putExtra(WeatherWidget.KEY_LOCATION_NAME, "-");
			intent.putExtra(WeatherWidget.KEY_WEATHER, "-");
			intent.putExtra(WeatherWidget.KEY_TEMPERATURE, "-");
		}
		
		sendBroadcast(intent);
		
	}
	
	public void UpdateWidgets() {
		
		try {
			SharedPreferences sharedPreferences = getSharedPreferences(NAME_SHARED_PREFERENCES, MODE_PRIVATE);
			JSONObject appWidgetConfigurations = new JSONObject(sharedPreferences.getString(KEY_APP_WIDGET_CONFIGURATIONS, "{}"));
			
			Iterator<String> i = appWidgetConfigurations.keys();
			
			while(i.hasNext()) {
				String appWidgetID = i.next();
				int position = appWidgetConfigurations.getInt(appWidgetID);
				UpdateWidget(Integer.parseInt(appWidgetID), position);
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
